<?php
/**
 * 数据库操作类
 * @author Zeyes <lixize8888@163.com>
 * @link http://www.zeyes.org
 * @copyright (c) 2015-2017 DotTimes
 * @version 1.0
 */

class Db
{
    protected $dbh = null;
    private $user, $pass, $dsn;

    /**
     * 构造函数
     * @param array $config = array(
     *              'dbms' => 'mysql',      //数据库类型
     *              'host' => 'localhost',  //数据库主机名
     *              'database' => 'test',   //使用的数据库
     *              'user' => 'root',       //数据库连接用户名
     *              'pass' => '12345678'    //对应的密码
     *             );
     */
    public function __construct($config)
    {
        if(!isset($config['dbms'])) $config['dbms'] = 'mysql';
        if(!isset($config['host'])) $config['host'] = 'localhost';
        if(isset($config['user'])) $this->user = $config['user'];
        else $this->user = 'root';

        if(!isset($config['database']) || !isset($config['pass'])) 
            $this->dsn = null; 
        else 
        {
            $this->dsn = $config['dbms'].":host=".$config['host'].
                         ";dbname=".$config['database'];
            $this->pass = $config['pass'];
        }
    }

    /**
     * 数据库连接
     * @param null
     * @return boolean 是否连接成功
     */

    public function connect()
    {
        try{
            $this->dbh = new PDO($this->dsn, $this->user, $this->pass);
            if($this->dbh) return true;
        }catch(PDOException $e)
        {
            //echo "Error!: " . $e->getMessage() . "\n";
        }
        return false;
    }

    /**
     * query查询
     * @param string $sql SQL语句
     * @return array SQL返回的结果集 
     */
    public function query($sql)
    {
        if($this->dbh) 
        {
            $obj = $this->dbh->query($sql);
            if($obj) { $result = $obj->fetchAll(); $obj->closeCursor(); }
            else $result = null;
        }
        else $result = null;
        return $result;
    }

    /**
     * exec 查询
     * @param string $sql SQL语句
     * @return array SQL返回的结果集 
     */

    public function exec($sql)
    {
        $count = -1;
        if($this->dbh) $count = $this->dbh->exec($sql);
        return $count;
    }

    /**
     * 字符串转义
     * @param string $str 要转义的字符串
     * @return string 转义后的字符串
     */
    public function quote($str)
    {
        return $this->dbh->quote($str);
    }

    /**
     * 获取上次插入成功的id
     * @return string 转义后的字符串
     */
    public function lastInsertId()
    {
        return $this->dbh->lastInsertId();
    }
}
?>
